package com.promise.jokerdream.ui.timer

import androidx.activity.compose.BackHandler
import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.gestures.detectHorizontalDragGestures
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Delete
import androidx.compose.material3.*
import androidx.compose.runtime.*
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.input.pointer.pointerInput
import androidx.compose.ui.platform.LocalContext
import androidx.navigation.NavController
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import com.promise.jokerdream.database.entity.TimerTaskConfigEntity
import com.promise.jokerdream.database.UserDataManager
import com.promise.jokerdream.ui.components.DangerAlertDialog
import com.promise.jokerdream.ui.components.RoundCheckbox
import com.promise.jokerdream.ui.components.TaskNameInputDialog
import com.promise.jokerdream.ui.theme.AppColors
import com.promise.jokerdream.ui.theme.AppSpacing
import com.promise.jokerdream.ui.toolbar.AppTopBar
import com.promise.jokerdream.navigation.AppRoute
import java.util.UUID

/**
 * 定时任务页面
 */
@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun TimerPage(
    userId: String,
    navController: NavController,
    modifier: Modifier = Modifier,
    onBackClick: () -> Unit,
    onNavigateToExecutionLog: () -> Unit = {}
) {
    val context = LocalContext.current
    val userDataManager = remember { UserDataManager.getInstance(context) }
    
    // 处理返回手势
    BackHandler {
        onBackClick()
    }
    
    // 状态管理
    var timerTasks by remember { mutableStateOf<List<TimerTaskConfigEntity>>(emptyList()) }
    var showTaskNameDialog by remember { mutableStateOf(false) }
    var showDeleteDialog by remember { mutableStateOf(false) }
    var taskToDelete by remember { mutableStateOf<TimerTaskConfigEntity?>(null) }
    var swipedTaskId by remember { mutableStateOf<String?>(null) }
    
    // 加载定时任务数据
    LaunchedEffect(userId) {
        val account = userDataManager.getUserAccount(userId)
        timerTasks = account?.config?.timerTaskConfig ?: emptyList()
    }
    
    // 同步定时任务到数据库的函数
    fun syncTimerTasksToUserConfig(
        userDataManager: UserDataManager,
        userId: String,
        updatedTimerTasks: List<TimerTaskConfigEntity>
    ) {
        kotlinx.coroutines.runBlocking(kotlinx.coroutines.Dispatchers.IO) {
            try {
                for (task in updatedTimerTasks) {
                    userDataManager.updateTimerTask(userId, task)
                }
            } catch (e: Exception) {
                e.printStackTrace()
            }
        }
    }
    
    Column(
        modifier = modifier.fillMaxSize()
    ) {
        // 顶部导航栏
        AppTopBar(
            title = "定时任务",
            onBackClick = onBackClick,
            actionIcon = {
                Button(
                    onClick = { showTaskNameDialog = true },
                    modifier = Modifier.height(28.dp),
                    colors = ButtonDefaults.buttonColors(
                        containerColor = MaterialTheme.colorScheme.primary
                    ),
                    contentPadding = PaddingValues(horizontal = AppSpacing.componentLarge)
                ) {
                    Text(
                        text = "新建",
                        fontSize = 14.sp,
                        color = MaterialTheme.colorScheme.onPrimary
                    )
                }
            }
        )
        
        // 定时任务列表
        if (timerTasks.isEmpty()) {
            // 空状态
            Box(
                modifier = Modifier
                    .fillMaxSize()
                    .background(AppColors.PageBackground)
                    .padding(AppSpacing.pageHorizontal),
                contentAlignment = Alignment.Center
            ) {
                Column(
                    horizontalAlignment = Alignment.CenterHorizontally
                ) {
                    Text(
                        text = "暂无定时任务",
                        fontSize = 18.sp,
                        fontWeight = FontWeight.Medium,
                        color = MaterialTheme.colorScheme.onSurface,
                        textAlign = TextAlign.Center
                    )
                    
                    Spacer(modifier = Modifier.height(8.dp))
                    
                    Text(
                        text = "点击右上角\"新建\"按钮创建定时任务",
                        fontSize = 14.sp,
                        color = MaterialTheme.colorScheme.onSurfaceVariant,
                        textAlign = TextAlign.Center
                    )
                }
            }
        } else {
            // 任务列表
            LazyColumn(
                modifier = Modifier
                    .fillMaxSize()
                    .background(AppColors.PageBackground)
                    .padding(AppSpacing.pageHorizontal),
                verticalArrangement = Arrangement.spacedBy(12.dp),
                contentPadding = PaddingValues(vertical = 16.dp)
            ) {
                items(timerTasks) { task ->
                    TimerTaskItem(
                        task = task,
                        onTaskClick = { 
                            navController.navigate("${AppRoute.TimerTaskConfig.route.replace("{taskId}", task.taskId)}")
                        },
                        onTaskToggle = { 
                            val updatedTasks = timerTasks.map { 
                                if (it.taskId == task.taskId) it.copy(isEnabled = !it.isEnabled) else it 
                            }
                            timerTasks = updatedTasks
                            syncTimerTasksToUserConfig(userDataManager, userId, updatedTasks)
                        },
                        onTaskEdit = { 
                            navController.navigate("${AppRoute.TimerTaskConfig.route.replace("{taskId}", task.taskId)}")
                        },
                        onTaskDelete = { 
                            taskToDelete = task
                            showDeleteDialog = true
                        },
                        isSwiped = swipedTaskId == task.taskId,
                        onSwipe = { taskId -> swipedTaskId = taskId }
                    )
                }
            }
        }
    }
    
    // 任务名称输入对话框
    TaskNameInputDialog(
        show = showTaskNameDialog,
        onTaskNameEntered = { taskName ->
            showTaskNameDialog = false
            // 创建新的定时任务
            val newTaskId = UUID.randomUUID().toString()
            val newTask = TimerTaskConfigEntity(
                id = 0, // 自增主键
                userId = userId,
                taskId = newTaskId,
                taskName = taskName,
                startTime = "06:00", // 默认开始时间
                endTime = "18:00",   // 默认结束时间
                isEnabled = true,
                lastExecutedDate = null
            )
            
            // 添加到本地状态
            val updatedTasks = timerTasks + newTask
            timerTasks = updatedTasks
            
            // 同步到UserConfig
            syncTimerTasksToUserConfig(userDataManager, userId, updatedTasks)
            
            // 跳转到配置页面
            navController.navigate("${AppRoute.TimerTaskConfig.route.replace("{taskId}", newTaskId)}")
        },
        onDismiss = { showTaskNameDialog = false }
    )
    
    // 删除确认对话框
    DangerAlertDialog(
        show = showDeleteDialog,
        title = "删除定时任务",
        content = "确定要删除定时任务\"${taskToDelete?.taskName}\"吗？此操作不可撤销。",
        confirmText = "删除",
        cancelText = "取消",
        onDismiss = { 
            showDeleteDialog = false
            taskToDelete = null
            swipedTaskId = null
        },
        onConfirm = {
            taskToDelete?.let { task ->
                val updatedTasks = timerTasks.filter { it.taskId != task.taskId }
                timerTasks = updatedTasks
                syncTimerTasksToUserConfig(userDataManager, userId, updatedTasks)
                // 删除数据库中的任务
                userDataManager.deleteTimerTask(task.taskId)
            }
            showDeleteDialog = false
            taskToDelete = null
            swipedTaskId = null
        }
    )
}

/**
 * 定时任务项组件
 */
@Composable
private fun TimerTaskItem(
    task: TimerTaskConfigEntity,
    onTaskClick: () -> Unit,
    onTaskToggle: () -> Unit,
    onTaskEdit: () -> Unit,
    onTaskDelete: () -> Unit,
    isSwiped: Boolean,
    onSwipe: (String?) -> Unit,
    modifier: Modifier = Modifier
) {
    var offsetX by remember { mutableStateOf(0f) }
    val swipeThreshold = 80f
    
    // 当其他任务项开始滑动时，重置当前项的滑动状态
    LaunchedEffect(isSwiped) {
        if (!isSwiped) {
            offsetX = 0f
        }
    }
    
    Box(
        modifier = modifier
            .fillMaxWidth()
            .height(120.dp)
    ) {
        // 删除按钮背景 - 跟随手势左滑拉出
        if (offsetX < 0) {
            Box(
                modifier = Modifier
                    .fillMaxHeight()
                    .width((-offsetX).dp)
                    .background(Color.Red)
                    .align(Alignment.CenterEnd)
            ) {
                Box(
                    modifier = Modifier
                        .fillMaxSize()
                        .clickable { onTaskDelete() },
                    contentAlignment = Alignment.Center
                ) {
                    Icon(
                        imageVector = Icons.Default.Delete,
                        contentDescription = "删除任务",
                        tint = Color.White,
                        modifier = Modifier.size(24.dp)
                    )
                }
            }
        }
        
        // 任务项
        Box(
            modifier = Modifier
                .fillMaxWidth()
                .fillMaxHeight()
                .offset(x = offsetX.dp)
                .background(
                    color = MaterialTheme.colorScheme.surface,
                    shape = RoundedCornerShape(12.dp)
                )
                .pointerInput(Unit) {
                    detectHorizontalDragGestures(
                        onDragStart = { onSwipe(task.taskId) },
                        onDragEnd = {
                            if (offsetX < -swipeThreshold/2) {
                                offsetX = -swipeThreshold
                            } else {
                                offsetX = 0f
                                onSwipe(null)
                            }
                        }
                    ) { _, x ->
                        if (x < 0) {
                            offsetX = (offsetX + x).coerceAtLeast(-swipeThreshold)
                        } else if (offsetX < 0) {
                            offsetX = (offsetX + x).coerceAtMost(0f)
                        }
                    }
                }
                .clickable { 
                    if (offsetX == 0f) {
                        onTaskClick()
                    }
                }
        ) {
            Column(
                modifier = Modifier
                    .fillMaxWidth()
                    .padding(16.dp)
            ) {
                // 标题行 - 参考SettingCard的布局
                Row(
                    modifier = Modifier.fillMaxWidth(),
                    verticalAlignment = Alignment.CenterVertically,
                    horizontalArrangement = Arrangement.spacedBy(12.dp)
                ) {
                    // RoundCheckbox
                    RoundCheckbox(
                        checked = task.isEnabled,
                        onCheckedChange = { onTaskToggle() }
                    )
                    
                    // 任务标题
                    Text(
                        text = task.taskName,
                        fontSize = 16.sp,
                        fontWeight = FontWeight.SemiBold,
                        color = if (task.isEnabled) 
                            MaterialTheme.colorScheme.onSurface 
                        else 
                            MaterialTheme.colorScheme.onSurfaceVariant,
                        maxLines = 1,
                        overflow = TextOverflow.Ellipsis,
                        modifier = Modifier.weight(1f)
                    )
                }
                
                // 内容区域 - 展示任务执行时间和状态
                Spacer(modifier = Modifier.height(12.dp))
                Column(
                    verticalArrangement = Arrangement.spacedBy(4.dp)
                ) {
                    Text(
                        text = "任务执行时间: ${task.startTime}-${task.endTime}",
                        fontSize = 14.sp,
                        fontWeight = FontWeight.Medium,
                        color = MaterialTheme.colorScheme.onSurface
                    )
                    
                    Text(
                        text = "任务状态: ${if (task.isTodayExecuted()) "今日已执行" else "今日未执行"}",
                        fontSize = 14.sp,
                        fontWeight = FontWeight.Medium,
                        color = if (task.isTodayExecuted()) 
                            MaterialTheme.colorScheme.primary 
                        else 
                            AppColors.Error
                    )
                }
            }
        }
    }
}
